package org.geekbang.thinking.in.spring.ioc.overview.dependency.injection;

import org.geekbang.thinking.in.spring.ioc.overview.domain.User;
import org.geekbang.thinking.in.spring.ioc.overview.repository.UserRepository;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.env.Environment;

/**
 * 依赖注入
 */
public class DependencyInjectionDemo {

    public static void main(String[] args) {

        BeanFactory beanFactory = new ClassPathXmlApplicationContext("classpath:/META-INF/dependency-injection-context.xml");
        //依赖来源一：自定义 bean
        UserRepository userRepository = beanFactory.getBean("userRepository", UserRepository.class);
        System.out.println("实时查找："+userRepository);
        //依赖来源二：依赖注入 (内建依赖)
        System.out.println(userRepository.getBeanFactory());
        //依赖查找，会报错 No qualifying bean of type 'org.springframework.beans.factory.BeanFactory' available
//        BeanFactory beanFactory1 = beanFactory.getBean(BeanFactory.class);
//        System.out.println(beanFactory1);
        //依赖注入的来源和依赖查找的来源不同

        ObjectFactory<User> userObjectFactory = userRepository.getUserObjectFactory();
        System.out.println(userObjectFactory.getObject());

        //依赖来源三：容器内建 bean
        Environment environment = beanFactory.getBean(Environment.class);
        System.out.println("获取 Environment 类型的 Bean"+environment);
    }
}
